package util;

import com.google.gson.*;
import org.apache.commons.lang3.StringUtils;
import org.scribe.builder.ServiceBuilder;
import org.scribe.model.*;
import org.scribe.oauth.OAuthService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * java调用NS的Restlet脚本
 * 官方Demo: https://netsuite.custhelp.com/app/answers/detail/a_id/42167
 * 消费者/令牌的密钥密码设置（包含功能所处位置）: https://5141176-sb1.app.netsuite.com/app/help/helpcenter.nl?fid=section_4636902750.html
 */
public class NsRestletUtil {

    private static OAuthService getService(String consumerKey, String consumerSecret) {
        return new ServiceBuilder()
                .provider(DummyService.class)
                .apiKey(consumerKey)
                .apiSecret(consumerSecret)
                .signatureType(SignatureType.Header)
                .build();
    }

    private static Token getToken(String tokenId, String tokenSecret) {
        return new Token(tokenId, tokenSecret);
    }

    private static OAuthRequest getGetRequest(String realm, String url, String paramStr) {

        paramStr = StringUtils.isEmpty(paramStr) ? "" : paramStr;

        OAuthRequest request = new OAuthRequest(Verb.GET, url + paramStr);
        request.setCharset("UTF-8");
        request.setRealm(realm);

        return request;
    }

    private static OAuthRequest getPostRequest(String realm, String url, Map<String, String> headerMap, String bodyParamJsonStr) {
        OAuthRequest request = new OAuthRequest(Verb.POST, url);
        request.setCharset("UTF-8");
        request.setRealm(realm);
        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            request.addHeader(entry.getKey(), entry.getValue());
        }
        request.addPayload(bodyParamJsonStr);

        return request;
    }

    public static Response callWithHttpGet(String url, String realm, String consumerKey
            , String consumerSecret, String tokenId, String tokenSecret, String paramStr){

        OAuthRequest request = getGetRequest(realm, url, paramStr);

        OAuthService oAuthService = getService(consumerKey, consumerSecret);
        Token accessToken = getToken(tokenId, tokenSecret);

        oAuthService.signRequest(accessToken, request);

        return request.send();
    }

    public static Response callWithHttpPost(String url, String realm, String consumerKey, String consumerSecret
            , String tokenId, String tokenSecret, Map<String, String> map, String bodyParamJsonStr){

        Map<String, String> headerMap = new HashMap<String, String>();
        headerMap.put("content-type", "application/json;charset=utf-8");
        if (map != null && !map.isEmpty()) {
            headerMap.putAll(map);
        }

        OAuthRequest request = getPostRequest(realm, url, headerMap, bodyParamJsonStr);

        OAuthService oAuthService = getService(consumerKey, consumerSecret);
        Token accessToken = getToken(tokenId, tokenSecret);

        oAuthService.signRequest(accessToken, request);

        return request.send();
    }


    public static void main(String[] args) {
        // get
//        Response response = callWithHttpGet(NsRestleConstant.REST_URL_1, NsRestleConstant.REALM,
//                NsRestleConstant.CONSUMER_KEY_1, NsRestleConstant.CONSUMER_SECRET_1,
//                NsRestleConstant.TOKEN_ID_1, NsRestleConstant.TOKEN_SECRET_1 , "&id=4");
//        System.out.println(response.getBody());

        // post
//        String bodyParamJsonStr = getPostParamJsonStr();
//        Response response = callWithHttpPost(NsRestleConstant.REST_URL_1, NsRestleConstant.REALM,
//                NsRestleConstant.CONSUMER_KEY_1, NsRestleConstant.CONSUMER_SECRET_1,
//                NsRestleConstant.TOKEN_ID_1, NsRestleConstant.TOKEN_SECRET_1 , null, bodyParamJsonStr);
//
//        // 响应体内容
//        String jsonStr = response.getBody();
//        System.out.println(jsonStr);
//
//        parsePostResponseBody(jsonStr);


    }

    /**
     * {
     *     "str": "wwj",
     *     "arr": [
     *         {
     *             "arrStr": "wwj-1",
     *             "double": 1.234,
     *             "integer": 1234
     *         },
     *         {
     *             "arrStr": "wwj-2",
     *             "double": 1.235,
     *             "integer": 1235
     *         }
     *     ],
     *     "double": 1.23,
     *     "integer": 123
     * }
     */
    public static String getPostParamJsonStr() {
        Gson gson = new Gson();

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("str", "wwj");
        paramMap.put("integer", 123);
        paramMap.put("double", 1.23);

        List<Map<String, Object>> paramArrMapList = new ArrayList<Map<String, Object>>();

        Map<String, Object> paramArrMap = new HashMap<String, Object>();
        paramArrMap.put("arrStr", "wwj-1");
        paramArrMap.put("integer", 1234);
        paramArrMap.put("double", 1.234);

        Map<String, Object> paramArrMap2 = new HashMap<String, Object>();
        paramArrMap2.put("arrStr", "wwj-2");
        paramArrMap2.put("integer", 1235);
        paramArrMap2.put("double", 1.235);

        paramArrMapList.add(paramArrMap);
        paramArrMapList.add(paramArrMap2);

        paramMap.put("arr", paramArrMapList);

        String jsonStr = gson.toJson(paramMap);
        System.out.println(jsonStr);

        return jsonStr;
    }

    public static void parsePostResponseBody(String responseBodyStr) {
        // 转换为json对象
        JsonObject jsonObject = new JsonParser().parse(responseBodyStr).getAsJsonObject();
        System.out.println(jsonObject.get("str").getAsString());
        System.out.println(jsonObject.get("integer").getAsInt());
        System.out.println(jsonObject.get("double").getAsDouble());

        JsonArray jsonArray = jsonObject.getAsJsonArray("arr");
        for (JsonElement jsonElement : jsonArray) {
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject2 = jsonElement.getAsJsonObject();
                System.out.println(jsonObject2.get("arrStr").getAsString());
                System.out.println(jsonObject2.get("double").getAsDouble());
                System.out.println(jsonObject2.get("integer").getAsInt());
            }
        }
    }


}
